﻿using PARK.Common.Core.Manager;
using PARK.Common.Enum;
using PARK.Common.Extension;
using PARK.Common.Filter;
using PARK.Dependency;
using PARK.DynamicApiController;
using PARK.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Yitter.IdGenerator;
using PARK.Common.Helper;
using PARK.JsonSerialization;
using PARK.Accessctl.Entitys;
using System.Text;
using System.Data;
using PARK.Attend.Interfaces.AttendMachs;
using PARK.Attend.Entitys;
using PARK.Attend.Entitys.Dto.AttendMachs;

namespace PARK.Attend.AttendMachs
{
    /// <summary>
    /// 考勤设备服务
    /// </summary>
    [ApiDescriptionSettings(Tag = "Attend", Name = "Machs", Order = 200)]
    [Route("api/attend/[controller]")]
    public class AttendMachsService : IAttendMachsService, IDynamicApiController, ITransient
    {
        private readonly ISqlSugarRepository<AttendMachsEntity> _attendMachsRepository;
        private readonly SqlSugarScope _db;
        private readonly IUserManager _userManager;

        /// <summary>
        /// 初始化一个<see cref="AttendMachsService"/>类型的新实例
        /// </summary>
        public AttendMachsService(
            ISqlSugarRepository<AttendMachsEntity> attendMachsRepository,
            IUserManager userManager)
        {
            _attendMachsRepository = attendMachsRepository;
            _db = _attendMachsRepository.Context;
            _userManager = userManager;
        }

        /// <summary>
        /// 获取考勤设备
        /// </summary>
        /// <param name="id">参数</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<dynamic> GetInfo(string id)
        {
            var entity = await _db.Queryable<AttendMachsEntity>().FirstAsync(p => p.machlId == id);
            var output = entity.Adapt<AttendMachsInfoOutput>();
            return output;
        }

        /// <summary>
		/// 获取考勤设备列表
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [HttpGet("")]
        public async Task<dynamic> GetList([FromQuery] AttendMachsListQueryInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var sidx = input.sidx == null ? "machlId" : input.sidx;
                var data = await _db.Queryable<AttendMachsEntity>()
                    //公司权限
                    .Where(p => p.CompanyId.Equals(userInfo.companyId))
                    .Where(p => p.IsDeleted == 0)
                    .WhereIF(!string.IsNullOrEmpty(input.keyword), p => p.machName.Contains(input.keyword) || p.machSN.Contains(input.keyword) || p.IoTcardNo.Contains(input.keyword))
                    .WhereIF(!string.IsNullOrEmpty(input.doorAreaId), p => p.DoorAreaId.Equals(input.doorAreaId))
                    .WhereIF(!string.IsNullOrEmpty(input.isOnline), p => p.IsOnline.Equals(input.isOnline))
                    .Select(it => new AttendMachsListOutput
                    {
                        machlId = it.machlId,
                        machName = it.machName,
                        machSN = it.machSN,
                        doorAreaId = it.DoorAreaId,
                        doorAreaName = it.DoorAreaName,
                        ctlposition = it.Ctlposition,
                        ioTcardNo = it.IoTcardNo,
                        ioTcardvalidity = it.IoTcardvalidity,
                        enabledMark = it.EnabledMark,
                        description = it.Description,
                        isOnline = it.IsOnline,
                        lastOnLineTime = it.LastOnLineTime,
                        isSyntime = it.IsSyntime,
                        lastSyntime = it.LastSyntime
                    }).MergeTable().OrderBy(sidx + " " + input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
                return PageResult<AttendMachsListOutput>.SqlSugarPageResult(data);
            }
            else
                return null;
        }

        #region Post
        /// <summary>
        /// 新建考勤设备
        /// </summary>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPost("")]
        public async Task Create([FromBody] AttendMachsCrInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var entity = input.Adapt<AttendMachsEntity>();
                entity.CompanyId = userInfo.companyId;
                entity.CompanyName = userInfo.companyName;
                entity.machlId = YitIdHelper.NextId().ToString();
                try
                {
                    var data = await _db.Queryable<AttendMachsEntity>().Where(t => t.IsDeleted == 0 && t.machSN == entity.machSN && t.CompanyId == userInfo.companyId).ToListAsync();
                    if (data.Count > 0)
                    {
                        throw PARKException.Bah("所填写[考勤机SN]已存在!");
                    }
                    else
                    {
                        //开启事务
                        _db.BeginTran();
                        //新增考勤设备记录
                        entity.Create();
                        await _db.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteReturnEntityAsync();
                        //关闭事务
                        _db.CommitTran();
                    }
                }
                catch (Exception ex)
                {
                    //回滚事务
                    _db.RollbackTran();
                    throw PARKException.Oh(ErrorCode.COM1000);
                }
            }
            else
                throw PARKException.Bah("您的权限无法操作!");
        }
        /// <summary>
        /// 更新考勤设备
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task Update(string id, [FromBody] AttendMachsUpInput input)
        {
            var entity = input.Adapt<AttendMachsEntity>();
            try
            {
                //开启事务
                _db.BeginTran();
                entity.LastModify(id);
                //更新门禁设备记录
                await _db.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
                //关闭事务
                _db.CommitTran();
            }
            catch (Exception)
            {
                //回滚事务
                _db.RollbackTran();
                throw PARKException.Oh(ErrorCode.COM1001);
            }
        }
        /// <summary>
        /// 删除考勤设备
        /// </summary>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task Delete(string id)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var entity = await _db.Queryable<AttendMachsEntity>().FirstAsync(p => p.machlId == id);
                _ = entity ?? throw PARKException.Oh(ErrorCode.COM1005);
                try
                {
                    //开启事务
                    _db.BeginTran();
                    //删除门禁设备记录
                    await _db.Deleteable<AttendMachsEntity>().Where(d => d.machlId == id).ExecuteCommandAsync();
                    //关闭事务
                    _db.CommitTran();
                }
                catch (Exception)
                {
                    //回滚事务
                    _db.RollbackTran();
                    throw PARKException.Oh(ErrorCode.COM1002);
                }
            }
            else
                throw PARKException.Bah("您的权限无法操作!");
        }
        #endregion

        #region 获取考勤设备状态统计
        /// <summary>
        /// 获取考勤设备状态统计
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("GetAttendStatusCenQtys")]
        public async Task<dynamic> GetAttendStatusCenQtys([FromQuery] AttendMachsListQueryInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                try
                {
                    StringBuilder dbSql = new StringBuilder("select isOnline,count(0) as qty from attend_machs t where IsDeleted=0 ");

                    #region 查询条件
                    if (!string.IsNullOrEmpty(input.doorAreaId))
                    {
                        dbSql.AppendFormat(" AND t.DoorAreaId= '{0}'", input.doorAreaId);
                    }
                    if (!string.IsNullOrEmpty(input.keyword))
                    {
                        dbSql.AppendFormat(" AND (t.machName like '%{0}%' or t.machSN like '%{0}%' or t.IoTcardNo like '%{0}%')", input.keyword);
                    }
                    #endregion

                    //公司权限
                    dbSql.AppendFormat(" and CompanyId ='{0}'", userInfo.companyId);

                    dbSql.Append(" group by t.isOnline");
                    var data = await _db.SqlQueryable<DataTable>(dbSql.ToString()).ToDataTableAsync();
                    AttendStatusCenQtyOutput _output = new AttendStatusCenQtyOutput();
                    _output.onlineQty = 0;
                    _output.offlineQty = 0;
                    DataRow[] dr = data.Select("isOnline=0");
                    if (dr != null && dr.Length > 0)
                    {
                        _output.offlineQty = int.Parse(dr[0]["qty"].ToString());
                    }
                    dr = data.Select("isOnline=1");
                    if (dr != null && dr.Length > 0)
                    {
                        _output.onlineQty = int.Parse(dr[0]["qty"].ToString());
                    }
                    return _output;
                }
                catch (Exception)
                {
                    throw PARKException.Oh("获取数据异常");
                }
            }
            else
            {
                return null;
            }
        }
        #endregion

        /// <summary>
		/// 获取列表
		/// </summary>
		/// <returns></returns>
        [HttpGet("GetTransferList")]
        public async Task<dynamic> GetTransferList()
        {
            var userInfo = await _userManager.GetUserInfo();
            var data = await _db.Queryable<AttendMachsEntity>()
                //公司权限
                .Where(p => p.CompanyId.Equals(userInfo.companyId))
                 .Select(it => new AttendCtlTransferListOutput
                 {
                     machlId = it.machlId,
                     machName = it.machName
                 }).MergeTable().ToListAsync();
            return data;
        }
    }
}
